package Offer.offer2018;

import domain.TreeNode;

import java.util.LinkedList;
import java.util.List;

/**
 * 从上到下打印二叉树
 * Created by 雷文康 on 2018/3/11.
 */
public class Test23 {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(0);
        TreeNode p1 = new TreeNode(1);
        TreeNode p2 = new TreeNode(2);
        TreeNode p3 = new TreeNode(3);
        TreeNode p4 = new TreeNode(4);
        TreeNode p5 = new TreeNode(5);
        TreeNode p6 = new TreeNode(6);
        root.left = p1;
        root.right = p2;
        p1.left = p3;
        p1.right = p4;
        p2.left = p5;
        p2.right = p6;
        layerTraverse(root);
    }

    //从左到右遍历 0,1,2,3,4,5,6
    public static void layerTraverse(TreeNode root) {
        if (root == null) {
            return;
        }
        List<TreeNode> list = new LinkedList<>();
        list.add(root);
        while (!list.isEmpty()) {
            TreeNode node = list.remove(0);
            System.out.print(node.val);
            System.out.print(" ");
            if (node.left != null) {
                list.add(node.left);
            }
            if (node.right != null) {
                list.add(node.right);
            }
        }
    }

    //从左到右遍历 0,1,2,3,4,5,6
    public static void layerTraverse2(TreeNode root) {
        if (root == null) {
            return;
        }
        LinkedList<TreeNode> list = new LinkedList();
        list.add(root);
        while (!list.isEmpty()) {
            TreeNode node = list.remove();
            System.out.println(node.val);
            if (node.right != null) {
                list.add(node.right);
            }
            if (node.left != null) {
                list.add(node.left);
            }
        }

    }
}
